<template>
	<div class="category-manage-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">{{ mode === 'edit' ? '编辑分类' : '创建分类' }}</h2>

				<el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="120px">
					<!-- 分类名称 -->
					<el-form-item label="分类名称" prop="name" required>
						<el-input v-model="form.name" placeholder="请输入分类名称" maxlength="50" show-word-limit />
					</el-form-item>
				</el-form>
			</div>

			<!-- 右侧预览区域 -->
			<div class="preview-container">
				<h2 class="section-title">分类预览</h2>

				<div class="preview-details">
					<h3>{{ form.name || "未设置分类名称" }}</h3>

					<div class="meta-info">
						<p v-if="form.id"><strong>ID:</strong> {{ form.id }}</p>
						<p v-if="form.createdAt"><strong>创建时间:</strong> {{ formatDateTime(form.createdAt) }}</p>
						<p v-if="form.updatedAt"><strong>更新时间:</strong> {{ formatDateTime(form.updatedAt) }}</p>
						<p v-if="form.deleted !== undefined">
							<strong>状态:</strong>
							<el-tag :type="form.deleted === 0 ? 'success' : 'danger'">
								{{ form.deleted === 0 ? '正常' : '已删除' }}
							</el-tag>
						</p>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button type="primary" @click="handleSubmit">{{mode === 'edit' ? '修改分类' : '创建分类'}}</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'CategoryEditView',
	};
</script>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		getCategoriesDetails,
		saveCategories,
		updateCategories
	} from '@/api/shoppingCategories.js'

	const router = useRouter()
	const route = useRoute()
	const mode = route.params.mode // 'edit' 或 'add'
	const id = route.params.id // 编辑时有值，新增时为undefined
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const form = ref({
		id: "",
		name: "",
		deleted: 0,
		createdAt: "",
		updatedAt: ""
	});

	const formRef = ref(null)

	/**
	 * 表单校验规则
	 */
	const rules = {
		name: [{
				required: true,
				message: '请输入分类名称',
				trigger: 'blur'
			},
			{
				max: 50,
				message: '分类名称不能超过50个字符',
				trigger: 'blur'
			}
		]
	};

	/**
	 * 格式化日期显示
	 */
	const formatDateTime = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return date.toLocaleString();
	};

	/**
	 * 创建/修改分类
	 */
	const handleSubmit = async () => {
		try {
			await formRef.value.validate();

			// 调用创建或更新API
			const apiCall = mode === 'edit' ? updateCategories : saveCategories;
			const res = await apiCall(form.value);

			if (res.code === 200 || res.code === 204) {
				ElMessage.success(res.message || '操作成功');
				if (mode === 'add') {
					router.push({
						name: 'CategoryList'
					});
				} else {
					// 编辑模式，重新加载数据
					fetchCategoryData();
				}
			} else {
				ElMessage.error(res.message || '操作失败');
			}
		} catch (error) {
			console.error('提交失败:', error);
			ElMessage.error(`操作失败: ${error.message || '请检查表单数据'}`);
		}
	};

	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back();
			})
			.catch(() => {});
	};

	/**
	 * 获取分类详情
	 */
	const fetchCategoryData = async () => {
		loading.value = true;
		try {
			const res = await getCategoriesDetails(id);
			if (res.data) {
				form.value = res.data;
			}
		} catch (error) {
			ElMessage.error(res.message || '获取分类详情失败');
		} finally {
			loading.value = false;
		}
	};

	onMounted(() => {
		if (mode === 'edit' && id) {
			fetchCategoryData();
		}
	});
</script>

<style scoped>
	.category-manage-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 2;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.preview-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 20px;
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.preview-details h3 {
		font-size: 1.1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.meta-info {
		margin-top: 20px;
	}

	.meta-info p {
		margin-bottom: 10px;
		color: #6b7280;
		font-size: 0.875rem;
	}

	.meta-info strong {
		color: #4b5563;
		margin-right: 8px;
	}
</style>